<template>
  <div class="work_info">
    <van-nav-bar
        :title="$t('work_info')"
        left-arrow
        @click-left="$router.push($route.query.backName)"
    />
    <!--     身份信息-->
    <div style="padding: 10px">
      <div class="content_list">
        <!--        公司名称-->
        <div class="content_item" v-if="resourcesShow['corporateName'] === 1">
          <div>
            <img class="image" src="../../assets/icon_corporate_name.png">
            <span class="text">{{ $t('corporate_name') }}</span>
          </div>
          <input class="input" v-model="corporateName" :placeholder="$t('hint_input_corporate_name')"/>
        </div>
        <!--      行业类型-->
        <div class="content_item" @click="industryTypeClick" v-if="resourcesShow['workingLife'] === 1">
          <div>
            <img class="image" src="../../assets/icon_trade_type.png">
            <span class="text">{{ $t('industry_type') }}</span>
          </div>
          <div class="select_right">
            <span v-if="industryTypeText" class="select_right_text" style="color: #686666;">{{
                industryTypeText
              }}</span>
            <span v-else class="select_right_text">{{ $t('hint_input_industry_type') }}</span>
            <van-icon name="arrow" color="#9D9D9D"/>
          </div>
        </div>
        <!--        公司电话-->
        <div class="content_item" v-if="resourcesShow['workTelephone'] === 1">
          <div>
            <img class="image" src="../../assets/icon_contacts_tel.png">
            <span class="text">{{ $t('corporate_tel') }}</span>
          </div>
          <input class="input" v-model="workTelephone" :placeholder="$t('hint_input_corporate_tel')"/>
        </div>
        <!--      公司地址-->
        <div class="content_item" @click="addressClick" v-if="resourcesShow['companyDetailedAddress'] === 1">
          <div>
            <img class="image" src="../../assets/icon_corporate_address.png">
            <span class="text">{{ $t('corporate_address') }}</span>
          </div>
          <div class="select_right">
            <span v-if="companyDetailedAddress" class="select_right_text"
                  style=" color: #686666;">{{ companyDetailedAddress }}</span>
            <span v-else class="select_right_text">{{ $t('hint_select_corporate_name') }}</span>
            <van-icon name="arrow" color="#9D9D9D"/>
          </div>
        </div>
        <!--      在职时长-->
        <div class="content_item" @click="serviceLengthClick" v-if="resourcesShow['entryTime'] === 1">
          <div>
            <img class="image" src="../../assets/icon_shichang.png">
            <span class="text">{{ $t('length_service') }}</span>
          </div>
          <div class="select_right">
            <span v-if="entryTime" class="select_right_text" style="color: #686666;">{{
                entryTime
              }}</span>
            <span v-else class="select_right_text">{{ $t('hint_select_length_service') }}</span>
            <van-icon name="arrow" color="#9D9D9D"/>
          </div>
        </div>
        <!--      选择身份-->
        <div class="content_item" @click="identityClick" v-if="resourcesShow['workType'] === 1">
          <div>
            <img class="image" src="../../assets/icon_identity.png">
            <span class="text">{{ $t('choose_identity') }}</span>
          </div>
          <div class="select_right">
            <span v-if="identityText" class="select_right_text" style="color: #686666;">{{ identityText }}</span>
            <span v-else class="select_right_text">{{ $t('hint_select_identity') }}</span>
            <van-icon name="arrow" color="#9D9D9D"/>
          </div>
        </div>
        <!--        每月净收入-->
        <div class="content_item" v-if="resourcesShow['monthlyIncome'] === 1">
          <div>
            <img class="image" src="../../assets/icon_monthly_income.png">
            <span class="text">{{ $t('monthly_income') }}</span>
          </div>
          <input class="input" v-model="monthlyIncome" oninput="value = value.replace(/[^\d]/g, '')"
                 :placeholder="$t('hint_input_monthly_income')"/>
        </div>
        <!--      发薪日-->
        <div class="content_item" @click="salaryDayClick" v-if="resourcesShow['payday'] === 1">
          <div>
            <img class="image" src="../../assets/icon_calendar.png">
            <span class="text">{{ $t('pay_day') }}</span>
          </div>
          <div class="select_right">
            <span v-if="payday" class="select_right_text" style="color: #686666;">{{ payday }}</span>
            <span v-else class="select_right_text">{{ $t('hint_select_pay_day') }}</span>
            <van-icon name="arrow" color="#9D9D9D"/>
          </div>
        </div>

        <!--        行业类型选择面板-->
        <van-action-sheet v-model:show="industryTypeShow">
          <van-picker @confirm="industryTypeConfirm" @cancel="industryTypeShow = false"
                      :columns-field-names="{  text: 'value'}"
                      :columns="industryTypeColumns"/>
        </van-action-sheet>

        <!--       在职时长选择-->
        <van-action-sheet v-model:show="serviceLengthShow">
          <van-picker @confirm="serviceLengthConfirm" @cancel="serviceLengthShow = false"
                      :columns-field-names="{  text: 'value'}"
                      :columns="serviceLengthlColumns"/>
        </van-action-sheet>
        <!--      身份选择面板-->
        <van-action-sheet v-model:show="identityShow">
          <van-picker @confirm="identityConfirm" @cancel="identityShow = false"
                      :columns-field-names="{  text: 'value'}"
                      :columns="identityColumns"/>
        </van-action-sheet>
        <!--        学历选择面板-->
        <van-action-sheet v-model:show="salaryDayShow">
          <van-picker @confirm="salaryDayConfirm" @cancel="salaryDayShow = false"
                      :columns-field-names="{  text: 'value'}"
                      :columns="salaryDayColumns"/>
        </van-action-sheet>
        <!--        地址下拉选择-->
        <van-action-sheet v-model:show="addressShow">
          <div class="address_header">
            <div class="operation">
              <div class="cancel" @click="addressShow = false">{{ $t('cancel') }}</div>
              <div class="confirm" @click="addressConfirm">{{ $t('sure') }}</div>
            </div>
            <div class="input">
              <input v-model="detailsAddress" :placeholder="$t('hint_input_address_details')"/>
            </div>
          </div>
          <van-cascader
              v-model="addressValue"
              :options="addressColumns"
              :closeable="false"
              :field-names="{
                  text: 'name',
                  value: 'id',
                  children: 'children',
              }"
              @change="addressChange"
              @finish="addressFinish"
          />
        </van-action-sheet>
      </div>
      <!--      工作资料上传-->
      <div class="content_list work_box" style="margin-top: 10px;background-color: #ffffff">
        <div class="workInfo">
          <div class="title">
            <div class="round"></div>
            <div class="text">{{ $t('upload_data') }}</div>
          </div>
        </div>
        <div class="info_tags" v-if="resourcesShow['proofType'] === 1">
          <span class="item" v-for="item in tagsData" :key="item.id" @click="tagsClick(item)"
                :class="{item_active:proofType === item.key}">{{ item.value }}</span>
        </div>
        <div class="upload" v-if="resourcesShow['proofUrl'] === 1">
          <van-uploader accept="image/*" name="cover" :before-read="beforeRead" :after-read="updatePositive">
            <img v-if="dataImage" class="image" :src="dataImage">
            <img v-else class="image" src="../../assets/icon_front_card.png">
          </van-uploader>
        </div>
      </div>
      <div class="confirm">
        <button @click="confirm">{{ $t('finish') }}</button>
      </div>
    </div>
  </div>
</template>

<script>
import {ref, toRefs, reactive, computed} from 'vue'
import {useI18n} from 'vue-i18n'
import {Toast} from 'vant'
import {personalInfoSelect, selectCitys, saveWorkInfo, uploadWorkData} from '@/api/home'
import {debounce, setResourcesShow, processNext, compressImage} from '@/utils/tool'
import {useRoute} from "vue-router";
import {useStore} from "vuex";

export default {
  setup() {
    const {tm} = useI18n()
    const store = useStore()
    const currentDate = ref(new Date())
    // 所有下拉
    let allSelectData = ref([])
    let workInfo = reactive({
      corporateName: null,
      workingLife: null,
      workTelephone: null,
      companyDetailedAddress: null,
      monthlyIncome: null,
      entryTime: null,
      payday: null,
      proofType: 1,
      workType: null,
    })
    const routes = useRoute()
    const resourcesShow = ref({})
    // 资料认证
    const workData = reactive({
      dataImage: '',
      tagsClick: ({key}) => {
        workInfo.proofType = key
      },
      tagsData: computed(() => {
        return allSelectData.value.filter(item => item.type === 9)
      }),
      beforeRead: (file) => {
        return new Promise(async (resolve, reject) => {
          const fileType = ['image/jpeg', 'image/png', 'image/jpg']
          if (fileType.indexOf(file.type) === -1) {
            Toast('upload_image');
            reject()
          } else if (file.size < Math.pow(1024, 2)) {
            // 小于1m不压缩
            resolve(file)
          } else {
            // 压缩图片
            const caseFile = await compressImage(file)
            resolve(caseFile)
          }
        })
      },
      updatePositive: async (file) => {
        const formData = new FormData()
        formData.append('file', file.file)
        formData.append('type', 1)
        const res = await uploadWorkData(formData)
        if (res.code === 1) {
          workData.dataImage = res.data
        }
      }
    })
    // 行业类型
    let industryTypeSheet = reactive({
      industryTypeShow: false,
      industryTypeText: '',
      industryTypeColumns: [],
      industryTypeConfirm: (value) => {
        industryTypeSheet.industryTypeText = value.value
        workInfo.workingLife = value.key
        industryTypeSheet.industryTypeShow = false
      },
      industryTypeClick: () => {
        industryTypeSheet.industryTypeShow = true
        industryTypeSheet.industryTypeColumns = allSelectData.value.filter(item => item.type === 4)
      }
    })
    const getCitySelect = async (value) => {
      const res = await selectCitys({pid: value})
      if (res.code === 1) {
        return res.data
      }
    }
    // 选择地址
    let addressSheet = reactive({
      addressShow: false,
      addressColumns: [],
      detailsAddress: '',
      addressValue: '',
      addressFinishText: '',
      addressConfirm: () => {
        let {addressFinishText, detailsAddress} = addressSheet
        if (addressSheet.detailsAddress.length < 5) return Toast({message: tm('hint_address_to_five')})
        workInfo.companyDetailedAddress = addressFinishText + ' - ' + detailsAddress
        addressSheet.addressShow = false
      },
      addressClick: async () => {
        addressSheet.addressColumns = await getCitySelect(0)
        addressSheet.addressShow = true
      },
      addressChange: async ({value}) => {
        const filterList = async (data) => {
          for (let i = 0; i < data.length; i++) {
            if (data[i].children && data[i].children.length) {
              filterList(data[i].children)
            }
            if (value === data[i].id) {
              const list = await getCitySelect(value)
              if (list.length !== 0) {
                data[i].children = list
              }
              return
            }
          }
        }
        filterList(addressSheet.addressColumns)
      },
      addressFinish: ({selectedOptions}) => {
        addressSheet.addressFinishText = selectedOptions.map((option) => option.name).join(' - ');
      }
    })
    // 选择在职时长
    let serviceLengthSheet = reactive({
      serviceLengthShow: false,
      serviceLengthlColumns: [],
      serviceLengthConfirm: (value) => {
        workInfo.entryTime = value[0] + value[1]
        serviceLengthSheet.serviceLengthShow = false
      },
      serviceLengthClick: () => {
        const columns = [
          {
            values: [],
          },
          {
            values: [],
          }
        ]
        for (let i = 0; i < 70; i++) {
          columns[0].values.push(i + 1 + tm('pickerview_year'))
        }
        for (let i = 0; i < 12; i++) {
          columns[1].values.push(i + 1 + tm('pickerview_month'))
        }
        serviceLengthSheet.serviceLengthlColumns = columns
        serviceLengthSheet.serviceLengthShow = true
      }
    })
    // 选择身份
    let identitySheet = reactive({
      identityShow: false,
      identityText: '',
      identityColumns: [],
      identityConfirm: (value) => {
        identitySheet.identityText = value.value
        workInfo.workType = value.key
        identitySheet.identityShow = false
      },
      identityClick: () => {
        identitySheet.identityShow = true
        identitySheet.identityColumns = allSelectData.value.filter(item => item.type === 6)
      }
    })
    // 选择发薪日
    let salaryDaySheet = reactive({
      salaryDayShow: false,
      salaryDayColumns: [],
      salaryDayConfirm: (value) => {
        workInfo.payday = value
        salaryDaySheet.salaryDayShow = false
      },
      salaryDayClick: () => {
        salaryDaySheet.salaryDayShow = true
        const columns = []
        for (let i = 0; i < 31; i++) {
          columns.push(i + 1)
        }
        salaryDaySheet.salaryDayColumns = columns
      }
    })
    const verificationInfo = () => {
      let message = ''
      const {
        corporateName, workingLife, workTelephone, companyDetailedAddress, entryTime, payday, workType
      } = workInfo
      if (!corporateName && resourcesShow.value['corporateName'] === 1) return message = tm('hint_input_corporate_name')
      if (!workingLife && resourcesShow.value['workingLife'] === 1) return message = tm('hint_input_industry_type')
      if (!workTelephone && resourcesShow.value['workTelephone'] === 1) return message = tm('hint_input_corporate_tel')
      if (!companyDetailedAddress && resourcesShow.value['companyDetailedAddress'] === 1) return message = tm('hint_select_corporate_name')
      if (!entryTime && resourcesShow.value['entryTime'] === 1) return message = tm('hint_select_length_service')
      if (!payday && resourcesShow.value['payday'] === 1) return message = tm('hint_select_pay_day')
      if (!workType && resourcesShow.value['workType'] === 1) return message = tm('hint_select_identity')
      if (!workData.dataImage && resourcesShow.value['proofUrl'] === 1) return message = tm('hint_select_certification_photo')
      return message
    }
    const confirm = debounce(
        async () => {
          if (!verificationInfo()) {
            const res = await saveWorkInfo(workInfo)
            if (res.code === 1) {
              Toast({
                message: tm('submit_success')
              })
              processNext('workInfo', routes.query.backName)
            } else {
              Toast({
                message: res.message
              })
            }
          } else {
            Toast({
              message: verificationInfo()
            })
          }
        }
    )
    //获取所有下拉
    const getSelect = async () => {
      const res = await personalInfoSelect({
        countryType: 2,
      })
      allSelectData.value = res.data
      // 回显内容
      if (localStorage.getItem('userWriteInfo')) {
        const {
          workType,
          entryTime,
          corporateName,
          phone,
          companyDetailedAddress,
          monthlyIncome,
          payday,
          proofType,
          proofUrl
        } = JSON.parse(localStorage.getItem('userWriteInfo'))
        industryTypeSheet.industryTypeConfirm({
          value: allSelectData.value.filter(i => i.key === workType && i.type === 4)[0].value,
          key: workType
        })
        identitySheet.identityConfirm({
          value: allSelectData.value.filter(i => i.key === workType && i.type === 6)[0].value,
          key: workType
        })
        workInfo.entryTime = entryTime
        workInfo.corporateName = corporateName
        workInfo.workTelephone = phone
        workInfo.companyDetailedAddress = companyDetailedAddress
        workInfo.monthlyIncome = monthlyIncome
        workInfo.payday = payday
        workInfo.proofType = proofType
        workData.dataImage = proofUrl
      }
    }
    // 流程显示隐藏
    const getResourcesShow = async () => {
      resourcesShow.value = await setResourcesShow(3)
      // 清除loading
      store.dispatch('changeLoading', false)
    }
    getResourcesShow()
    getSelect()
    return {
      ...toRefs(industryTypeSheet),
      ...toRefs(addressSheet),
      ...toRefs(workInfo),
      ...toRefs(serviceLengthSheet),
      ...toRefs(identitySheet),
      ...toRefs(salaryDaySheet),
      ...toRefs(workData),
      resourcesShow,
      currentDate,
      allSelectData,
      confirm
    }
  },
}
</script>

<style scoped lang="less">
.work_info {
  background-color: #f2f3f5;
  overflow: auto;

  ::v-deep .van-nav-bar {
    background: linear-gradient(90deg, #FF5252, #FF8244) !important;
    z-index: 1999;
  }

  ::v-deep .van-nav-bar .van-icon {
    color: #333333 !important;
  }

  ::v-deep .van-cascader__header {
    display: none;
  }

  .address_header {
    font-size: 16px;
    padding: 0 10px;
    box-sizing: border-box;

    .operation {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .confirm {
        color: #FF5252;
      }
    }

    .input {
      width: 100%;
      margin-top: 10px;

      input {
        box-sizing: border-box;
        width: 100%;
        height: 35px;
        border-radius: 3px;
        padding: 5px 10px;
        outline: none;
        border: solid 1px #FF5252;
      }
    }
  }

  .content_list {
    border-radius: 5px;
    height: 100%;
    width: 100%;

    .content_item {
      height: 40px;
      border-bottom: solid 1px #f2f3f5;
      background-color: #ffffff;
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0 10px;

      div {
        height: 100%;
        display: flex;
        align-items: center;

        .image {
          height: 25px;
          width: 25px;
          margin-right: 10px;
        }

        .text {
          font-size: 12px;
          font-weight: 600;
        }
      }

      .select_right_text {
        color: #9D9D9D;
        font-size: 12px;
        margin-right: 5px;
      }

      .select_right {
        margin-right: 5px;
        margin-left: 5px;
        color: #333333;
        font-size: 12px;
        flex: 1;
        justify-content: flex-end;
      }

      .input {
        width: 180px;
        border: none;
        text-align: right;
        height: 25px;
        font-size: 12px;
      }
    }

    .workInfo {

      .title {
        display: flex;
        align-items: center;

        .round {
          height: 8px;
          width: 8px;
          border-radius: 50%;
          background-color: red;
          float: left;
          margin: 0px 10px 0 5px;
        }

        .text {
          font-weight: 600;
          font-size: 12px;
        }
      }

    }

    .info_tags {
      margin-top: 5px;
      margin-left: 5px;

      .item {
        display: inline-block;
        padding: 5px 12px;
        background-color: #EEEEEE;
        color: #939393;
        font-size: 12px;
        border-radius: 18px;
        margin-right: 15px;
        margin-bottom: 10px;
      }

      .item_active {
        color: #ffffff;
        background: linear-gradient(-45deg, #FF5252, #FF8C3C);
      }
    }

    .upload {
      margin-top: 10px;
      text-align: center;

      .image {
        height: 117.5px;
        width: 185px;
      }
    }
  }

  .work_box {
    padding: 10px;
    box-sizing: border-box;
  }

  .confirm {
    margin-top: 20px;
    text-align: center;

    button {
      width: 300px;
      padding: 10px 0;
      color: #ffffff;
      border: none;
      font-size: 16px;
      background: linear-gradient(-45deg, #FF5252, #FF8C3C);
      box-shadow: 0px 4px 10px 0px rgba(255, 92, 78, 0.52);
      border-radius: 29px;
    }

  }
}
</style>
